<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>异步</title>
</head>
<body>
  <script>
    function ajaxGet(url) {
     return new Promise((resolve,reject)=>{
       const xhr = new XMLHttpRequest();
       xhr.open('GET', url);
       xhr.send(null);
       xhr.onreadystatechange = function (e) {
         if (xhr.readyState === 4) {
           if (xhr.status === 200 && xhr.status < 300) {
             resolve(JSON.parse(xhr.responseText));
           }
         }
       };
       xhr.onerror = function (){
         reject('error')
       }
     })
    }
    // 将异步问题转换成了 链式调用 
    // ajaxGet('http://localhost:4005/test1')
    // .then(res1=>ajaxGet('http://localhost:4005/test2/'+res1.test1))
    // .then(res2=>ajaxGet('http://localhost:4005/test3/'+res2.test2))


    // 同步
    async function request(){
      const res1 = await ajaxGet('http://localhost:4005/test1');
      // 逻辑
      const res2 = await ajaxGet('http://localhost:4005/test2/'+res1.test1);
      // 逻辑
      const res3 = await ajaxGet('http://localhost:4005/test3/'+res2.test2);
    }

    request()
    // async await 

    // 回调地狱  : 异步里面回调套回调
    // ajaxGet('http://localhost:4005/test1', function (res1) {
    //   // 逻辑
    //   ajaxGet('http://localhost:4005/test2/'+res1.test1,(res2)=>{
    //     // 逻辑
    //     ajaxGet('http://localhost:4005/test3/'+res2.test2,(res3)=>{
    //       // 逻辑
    //       console.log(res3);
    //     })
    //   })
    // });

      // setTimeout(()=>{},1000) 调用第二个setTimeout 1000之后调用第三个setTimeout 成功
      // 通过同步的方式拿到 

      function setTime (time){
        return new Promise((resolve)=>{
          setTimeout(()=>{
            resolve('成功')
          },time)
        })
      }
      const fn = async ()=>{
        await setTime(1000) // 10
        await setTime(1000) // 20
        let res = await setTime(1000) //30 
        console.log(res)
      }

      fn()
  </script>
</body>
</html>